﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GS.Cricket.Web.mapclass;
using System.Text;
using System;
using System.Globalization;

namespace GS.Cricket.Web
{
    public partial class Fixtures : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["validuser"] != null)
            {
                if (!(Boolean)Session["validuser"])
                {
                    Panel_FixtureAdmin.Visible = false;
                }
            }
            else
            {
                Panel_FixtureAdmin.Visible = false;
            }


            if (!IsPostBack)
            {
                FixtureGridBind();

                var teamService = new GS.Cricket.Service.Impl.TeamService();
                var teams = teamService.GetAll();
                DropDownList_TeamA.DataSource = teams.Select(team => team);
                DropDownList_TeamA.DataTextField = "Name";
                DropDownList_TeamA.DataValueField = "Id";
                DropDownList_TeamA.DataBind();

                DropDownList_TeamB.DataSource = teams.Select(team => team);
                DropDownList_TeamB.DataTextField = "Name";
                DropDownList_TeamB.DataValueField = "Id";
                DropDownList_TeamB.DataBind();
            }
        }



        public void FixtureGridBind()
        {
            var matchService = new GS.Cricket.Service.Impl.MatchService();
            var matches = matchService.GetAllMatches().ToList();

            // Sort matches by date and time
            matches.Sort((x, y) => DateTime.Compare(x.Date, y.Date));

            var fixtures = new List<Fixture>();
            var teamService = new GS.Cricket.Service.Impl.TeamService();
            foreach (var match in matches)
            {
                var teamA = teamService.GetById(match.TeamA);
                var teamB = teamService.GetById(match.TeamB);
                if (teamA != null && teamB != null)
                {
                    var fixture = new Fixture()
                    {
                        Id = match.Id,
                        Name = new StringBuilder()
                                .Append(teamA.Name)
                                .Append(" -vs- ")
                                .Append(teamB.Name)
                                .ToString(),
                        MatchDate = match.Date.ToString("dd MMM yyyy - hh:mm tt"),
                        Winner = match.Winner == 0 ? "" : teamService.GetById(match.Winner).Name,
                        WonBy = String.Empty
                    };
                    fixtures.Add(fixture);
                }
            }

            if (fixtures.Count == 0)
            {
                var fixture = new Fixture()
                {
                    Id = -1,
                    Name = String.Empty,
                    MatchDate = String.Empty,
                    Winner = String.Empty,
                    WonBy = String.Empty
                };
                fixtures.Add(fixture);
            }
            MatchGrid.DataSource = fixtures.Select(fixture => fixture);
            MatchGrid.AutoGenerateColumns = false;
            MatchGrid.DataBind();
        }

        protected void ButtonAddFixture_Click(object sender, EventArgs e)
        {
            int teamA = Int32.Parse(DropDownList_TeamA.SelectedValue);
            int teamB = Int32.Parse(DropDownList_TeamB.SelectedValue);
            String matchDate = txtDate.Text.Trim();


            if (matchDate.Equals(String.Empty))
            {
                Label_FixtureError.Text = "Date field is empty";
            }
            else
            {
                DateTime result;
                if (!DateTime.TryParseExact(matchDate, "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result))
                {
                    Label_FixtureError.Text = "DateTime format is not valid. Format = dd-MM-yyyy HH:mm";
                }
                else
                {
                    var match = new GS.Cricket.Entities.Match()
                    {
                        Date = DateTime.ParseExact(matchDate, "dd-MM-yyyy HH:mm", null),
                        TeamA = teamA,
                        TeamB = teamB
                    };
                    var matchService = new GS.Cricket.Service.Impl.MatchService();
                    matchService.Add(match);
                    FixtureGridBind();
                }
            }
        }

        protected void Button_DeleteFixtureClick(object sender, EventArgs e)
        {
            if (MatchGrid.SelectedIndex < 0 || MatchGrid.SelectedValue == null)
            {
                Label_FixtureError.Text = "Please select a match first";
            }
            else
            {
                var matchId = MatchGrid.SelectedValue.ToString();
                var matchService = new GS.Cricket.Service.Impl.MatchService();
                matchService.Delete(Int32.Parse(matchId));

                // Delete all instance of this match from MatchTeam
                var matchTeamService = new GS.Cricket.Service.Impl.MatchTeamService();
                var mts = matchTeamService.GetAll();
                var mts2 = mts.Where(mt => mt.MatchId == Int32.Parse(matchId)).ToList();
                foreach (var mt in mts)
                {
                    matchTeamService.Delete(mt.Id);
                }

                // Delete all instance of this match from MatchPlayer
                var matchPlayerService = new GS.Cricket.Service.Impl.MatchPlayerService();
                var mps = matchPlayerService.GetAllMatchPlayers().Where(mp => mp.MatchId == Int32.Parse(matchId)).ToList();
                foreach (var mp in mps)
                {
                    matchPlayerService.Delete(mp.Id);
                }

                FixtureGridBind();
            }
        }


        #region Important! Select Row Capability
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            AddRowSelectToGridView(MatchGrid);
            base.Render(writer);
        }

        private void AddRowSelectToGridView(GridView gv)
        {
            foreach (GridViewRow row in gv.Rows)
            {
                row.Attributes["onmouseover"] = "this.style.cursor='pointer'";
                row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true));
            }
        }
        #endregion

    }
}